package org.zjx.swing.model;

import org.zjx.dom4j.XmlUtils1;
import org.zjx.entity.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class SceneModel {
    private Scene loadedScene;
    private String currentFilePath;
    private List<Room> roomList = new ArrayList<>();
    private List<WayPoint> wayPointList = new ArrayList<>();

    public SceneModel() {
        createNewScene();
    }

    public Scene getLoadedScene() {
        return loadedScene;
    }

    public String getCurrentFilePath() {
        return currentFilePath;
    }

    public void setCurrentFilePath(String currentFilePath) {
        this.currentFilePath = currentFilePath;
    }

    public List<Room> getRoomList() {
        return roomList;
    }

    public List<WayPoint> getWayPointList() {
        return wayPointList;
    }

    public void loadXmlFile(String filePath) throws Exception {
        String xml = new String(Files.readAllBytes(Paths.get(filePath)));
        loadedScene = XmlUtils1.xmlToObject(xml, Scene.class);
        currentFilePath = filePath;
        syncIndependentLists();
    }

    public void saveXmlFile(String filePath) throws Exception {
        loadedScene.setRooms(new ArrayList<>(roomList));
        loadedScene.setWayPoints(new ArrayList<>(wayPointList));
        String xml = XmlUtils1.objectToXml(loadedScene);
        Files.write(Paths.get(filePath), xml.getBytes());
    }

    public void createNewScene() {
        loadedScene = new Scene();
        loadedScene.setNpcs(new ArrayList<>());
        roomList.clear();
        wayPointList.clear();
        currentFilePath = null;
    }

    private void syncIndependentLists() {
        roomList.clear();
        if (loadedScene.getRooms() != null) {
            for (IRoom iRoom : loadedScene.getRooms()) {
                if (iRoom instanceof Room) {
                    roomList.add((Room) iRoom);
                }
            }
        }
        wayPointList.clear();
        wayPointList.addAll(loadedScene.getWayPoints());
    }

    public void validateScene(Scene scene) {
        if (scene.getName() == null || scene.getName().trim().isEmpty()) {
            throw new IllegalArgumentException("场景名称不能为空");
        }
        if (scene.getSize() == null) {
            throw new IllegalArgumentException("必须设置场景尺寸");
        }
    }
}